#!/usr/bin/env python
from google.appengine.ext import db
import CourseM

def getLecturesByCourse(course):
    query = db.Query(Lecture).filter('course =', course)
    return query.filter('deleted =',False).order('index')

def addLecture(name, courseKey):
    owner = GeneralM.getEmail()
    name=name.strip()
    course = CourseM.getCourseByKey(courseKey)
    if not course:
        return 'error: course not found'
    elif not owner:
        return 'error: user is not logged in'
    elif name == '':
        return 'error: Lecture name cannot be empty'
    elif db.Query(Lecture).filter('name =', name).filter('course =', course).count() > 0:
        return 'error: Lecture name already exists'
    else:
        lecture = Lecture(name = name, course = course, 
                          index = db.Query(Lecture).filter('course =', course).count())
        lecture.put()
        return lecture

def getLectureByKey(key):
    owner = GeneralM.getEmail()
    if owner and key:
        lecture = Lecture.get(key)
        if CourseM.isOwner(lecture.course):
            return lecture
        else:
            return 'error:user accessed lecture key or another user'
        
def getLecture(key):
    lecture = Lecture.get(key)
    return lecture

def lecture2Dict(lecture, withTopics=0):
    if withTopics:
        topics = TopicM.getTopicsByLecture(lecture)
    else:
        topics = None
    lectureDic = {
               'key' : lecture.key(),
               'name' : lecture.name,
               'topics' : topics
           }
    return lectureDic

def lecture2DictWith(lecture):
    return lecture2Dict(lecture, 1)
    
class Lecture(db.Model):
    course = db.ReferenceProperty(CourseM.Course)
    index = db.IntegerProperty()
    name = db.StringProperty()
    deleted = db.BooleanProperty(default=False)


import TopicM
import GeneralM    